import { globalShortcut, BrowserWindow } from 'electron'

type ShortcutHandler = () => void

class ShortcutManager {
  private static instance: ShortcutManager
  private shortcuts: Map<string, ShortcutHandler>

  private constructor() {
    this.shortcuts = new Map()
  }

  // 获取单例实例
  public static getInstance(): ShortcutManager {
    if (!ShortcutManager.instance) {
      ShortcutManager.instance = new ShortcutManager()
    }
    return ShortcutManager.instance
  }

  /**
   * 注册一个全局快捷键
   * @param accelerator 快捷键字符串 (例如 "CommandOrControl+Shift+X")
   * @param handler 快捷键触发时的回调函数
   */
  public register(accelerator: string, handler: ShortcutHandler): boolean {
    if (globalShortcut.isRegistered(accelerator)) {
      console.warn(`快捷键 ${accelerator} 已被注册`)
      return false
    }

    const success = globalShortcut.register(accelerator, handler)
    if (success) {
      this.shortcuts.set(accelerator, handler)
    } else {
      console.error(`快捷键 ${accelerator} 注册失败`)
    }
    return success
  }

  /**
   * 取消某个快捷键
   */
  public unregister(accelerator: string): void {
    if (globalShortcut.isRegistered(accelerator)) {
      globalShortcut.unregister(accelerator)
      this.shortcuts.delete(accelerator)
    }
  }

  /**
   * 取消所有快捷键
   */
  public unregisterAll(): void {
    globalShortcut.unregisterAll()
    this.shortcuts.clear()
  }

  /**
   * 发送消息给指定窗口
   */
  public sendToWindow(win: BrowserWindow, channel: string, ...args: any[]): void {
    if (win && !win.isDestroyed()) {
      win.webContents.send(channel, ...args)
    }
  }
}

export default ShortcutManager